package com.ambitor.ipro.actions;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.ambitor.grass.sql.dao.SuperDao;
import com.ambitor.grass.sql.dao.impl.SuperDaoImpl;
import com.ambitor.grass.util.data.DataMap;
import com.ambitor.grass.util.data.DatasetList;
import com.ambitor.grass.util.data.IData;
import com.ambitor.grass.util.data.IDataset;
import com.ambitor.ipro.app.gen.TaskGeneratorHelper;
import com.ambitor.ipro.entities.Result;
import com.ambitor.ipro.entities.TradeState;
import com.ambitor.ipro.entities.TradeType;
import com.ambitor.ipro.entities.UninstallSetting;
import com.ambitor.ipro.entities.UserProValidFlag;
import com.ambitor.ipro.service.TopService;
import com.ambitor.ipro.util.Constants;
import com.ambitor.ipro.util.IDataUtils;
import com.ambitor.ipro.util.ResultCode;
import com.ambitor.ipro.util.Utils;
import com.ambitor.ipro.view.Pager;
import com.taobao.api.domain.Item;
import com.taobao.api.domain.SellerCat;

public class UninstallIproAction extends JsonBaseAction {

	private static final long serialVersionUID = 1L;
	private transient SuperDao dao = null;
	private Result result = new Result(-1, "");

	public Result getResult() {
		return result;
	}

	public void setResult(Result result) {
		this.result = result;
	}

	public UninstallIproAction() throws SQLException {
		dao = new SuperDaoImpl(pd.getConn());
	}

	@Override
	public Pager getPager() {
		return pager;
	}

	@Override
	public IDataset getDataset() {
		return dataset;
	}

	@SuppressWarnings("unchecked")
	public String queryUsingBatch() throws Exception {
		String userId = pd.getTopUserId();
		IData param = new DataMap();
		param.put("VUSER_ID", userId);
		param.put("VVALID_FLAG", "1");
		IDataset usingBatch = dao.executeBaseOnSqlSql("TF_P_USER_PRO_BATCH",
				"SEL_BY_USERID_USING", param, pager.getFirst(), pager
						.getPageSize());
		usingBatch = Utils.getIntellSettings(dao, usingBatch);

		pager.setTotalCount(usingBatch.count());
		dataset.addAll(usingBatch);
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	public String querySomeCategory() throws Exception {
		IData param = new DataMap();
		param.put("VPRO_ID", pd.getRequestParameter("PRO_ID"));
		param.put("VVALID_FLAG", "1");
		IDataset someCategory = dao.executeBaseOnSqlSql("TF_P_USER_PRO_SUB",
				"SEL_SUB_BY_USERID", param, pager.getFirst(), pager
						.getPageSize());

		TopService topService = new TopService(Constants.EVN_SWITCH,
				Constants.APP_KEY_IMPROMOTION, Constants.APP_SECRET_IMPROMOTION);
		List<SellerCat> sellerCats = topService.getSellerCats(pd.getTopNick());
		for (int i = 0; i < someCategory.size(); i++) {
			for (SellerCat cat : sellerCats) {
				if (cat.getCid().toString().equals(
						someCategory.get(i, "CID").toString())) {
					someCategory.getData(i).put("CNAME", cat.getName());
				}
			}
		}

		pager.setTotalCount(someCategory.count());
		dataset.addAll(someCategory);

		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	public String queryCustom() throws Exception {
		IData param = new DataMap();
		param.put("VPRO_ID", pd.getRequestParameter("PRO_ID"));
		param.put("VVALID_FLAG", "1");
		IDataset custom = dao.executeBaseOnSqlSql("TF_P_USER_PRO_SUB",
				"SEL_SUB_BY_USERID", param, pager.getFirst(), pager
						.getPageSize());

		TopService topService = new TopService(Constants.EVN_SWITCH,
				Constants.APP_KEY_IMPROMOTION, Constants.APP_SECRET_IMPROMOTION);

		List<String> installIids = new ArrayList<String>();
		for (int i = 0; i < custom.size(); i++) {
			IData data = (IData) custom.get(i);
			installIids.add(data.getString("IID"));
		}

		if (installIids.size() > 0) {
			List<Item> itemList = topService.getItemsWithIids(pd
					.getTopSessionId(), "", installIids);
			IDataset itemIDataset = IDataUtils.itemsListToIDataset(itemList);
			for (int i = 0; i < custom.size(); i++) {
				IData data = (IData) custom.get(i);
				for (int y = 0; y < itemIDataset.count(); y++) {
					if (((IData) custom.get(i)).getString("IID").equals(
							((IData) itemIDataset.get(y)).getString("iid"))) {
						data.put("IMG", ((IData) itemIDataset.get(y))
								.getString("pic_url"));
						data.put("TITLE", ((IData) itemIDataset.get(y))
								.getString("title"));
					}
				}
			}
		}

		pager.setTotalCount(custom.count());
		dataset.addAll(custom);

		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	public String uninstallIntell() throws Exception {
		String proIds = pd.getRequestParameter("PRO_IDS");
		String installPlaces = pd.getRequestParameter("INSTALL_PLACES");
		if (StringUtils.isNotBlank(proIds)
				&& StringUtils.isNotBlank(installPlaces)) {
			String[] proIdArray = proIds.split(",");
			String[] installPlacesArray = installPlaces.split(",");

			IDataset tradeUninstalls = new DatasetList();
			IData tradeUninstall = new DataMap();
			for (int i = 0; i < proIdArray.length; i++) {
				unValidUserProBatch(proIdArray[i], pd.getTopUserId(),
						UserProValidFlag.UNVALID_UNINSTALL);

				tradeUninstall = new DataMap();
				tradeUninstall.put("PRIORITY", Constants.MIDDLE_PRIORITY);
				tradeUninstall.put("TRADE_STATE", TradeState.UN_EXECUTE);
				tradeUninstall.put("USER_ID", pd.getTopUserId());
				tradeUninstall.put("NICK", pd.getTopNick());
				tradeUninstall.put("TRADE_TYPE", TradeType.DEMAON_UNINSTALL);
				tradeUninstall.put("CREATE_TIME", pd.getTime());
				tradeUninstall.put("PLAN_EXEC_TIME", pd.getTime());
				tradeUninstall.put("PRO_ID", proIdArray[i]);
				tradeUninstall.put("UNINSTALL_SETTING",
						UninstallSetting.BATCH_UNINSTALL);
				tradeUninstall.put("PLACE", installPlacesArray[i]);
				tradeUninstall.put("REMARK", "按批次卸载");

				tradeUninstalls.add(tradeUninstall);
			}

			if (tradeUninstalls.size() > 0) {
				TaskGeneratorHelper.addTask(dao, tradeUninstalls);
			}

			result.setCode(ResultCode.SUCCESS);
			result.setMsg("");

		} else {
			result.setCode(ResultCode.ERROR);
			result.setMsg("传入参数错误，卸载失败，请联系我们");

		}

		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	private void unValidUserProBatch(String proId, String userId,
			String validFlag) throws Exception {
		IData param = new DataMap();
		param.put("VPRO_ID", proId);
		param.put("VUSER_ID", userId);
		param.put("VVALID_FLAG", validFlag);
		dao.executeBaseOnSqlSql("TF_P_USER_PRO_SUB", "UPDATE_BY_USERID_PROID",
				param);

		param.put("VEND_TIME", pd.getTime());
		dao.executeBaseOnSqlSql("TF_P_USER_PRO_BATCH",
				"UPDATE_BY_USERID_PROID", param);
	}

	@SuppressWarnings("unchecked")
	public String uninstallAll() throws Exception {
		String proIds = pd.getRequestParameter("PRO_IDS");
		if ("ALL".equals(proIds)) {
			unValidUserProBatch("-1", pd.getTopUserId(),
					UserProValidFlag.UNVALID_UNINSTALL);

			IData tradeUninstall = new DataMap();

			tradeUninstall = new DataMap();
			tradeUninstall.put("PRIORITY", String
					.valueOf(Constants.MIDDLE_PRIORITY));
			tradeUninstall.put("TRADE_STATE", TradeState.UN_EXECUTE);
			tradeUninstall.put("USER_ID", pd.getTopUserId());
			tradeUninstall.put("NICK", pd.getTopNick());
			tradeUninstall.put("TRADE_TYPE", TradeType.DEMAON_UNINSTALL);
			tradeUninstall.put("CREATE_TIME", pd.getTime());
			tradeUninstall.put("PLAN_EXEC_TIME", pd.getTime());
			tradeUninstall.put("UNINSTALL_SETTING",
					UninstallSetting.ALL_UNINSTALL);
			tradeUninstall.put("PLACE", "ALL");
			tradeUninstall.put("REMARK", "应急卸载");

			TaskGeneratorHelper.addTask(dao, tradeUninstall);

			result.setCode(ResultCode.SUCCESS);
			result.setMsg("");

		}
		return SUCCESS;
	}

}
